
Partial Class casePersonal
    Inherits System.Web.UI.Page
    Implements IPermission
    Implements IPageSave

    Public Property SaveVisible() As Boolean Implements IPageSave.SaveVisible
        Get
            Return Me.saveButton.Visible
        End Get
        Set(ByVal value As Boolean)
            Me.saveButton.Visible = value
        End Set
    End Property

    Public ReadOnly Property ControlCollection() As System.Web.UI.ControlCollection Implements IPermission.ControlCollection
        Get
            Return Me.Controls
        End Get
    End Property

    Public ReadOnly Property EntityPermissionType() As Cdm.DataCore.UserSecurity.Permission.PermissionType Implements IPermission.EntityPermissionType
        Get
            Return Cdm.DataCore.UserSecurity.Permission.PermissionType.CasePersonal
        End Get
    End Property

    Private Sub GetInfo(ByVal a As ServerValidateEventArgs)
    End Sub

    Public ReadOnly Property SectionName() As String Implements IPermission.SectionName
        Get
            Return "Personal"
        End Get
    End Property

    Public Property PrimaryObject() As Cdm.DataCore.ConfigurableObject Implements IPermission.PrimaryObject
        Get
            Return oParticipant
        End Get
        Set(ByVal value As Cdm.DataCore.ConfigurableObject)
            oParticipant = value
        End Set
    End Property

    Protected Property oParticipant() As Cdm.DataCore.Entities.Participant
        Get
            Return EntityController.GetParticipant()
        End Get
        Set(ByVal value As Cdm.DataCore.Entities.Participant)
            EntityController.SetParticipant(value)
        End Set
    End Property

    Protected Sub Page_Init(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Init

        If Not Me.IsPostBack Then

            If Not Request("ActiveTab") Is Nothing Then
                Me.EditCaseSubNav1.SelectedButton = Request("ActiveTab")
                SetActiveView()
            Else
                Me.CaseMultiView.ActiveViewIndex = 0
            End If

            'If Request("participantid") Is Nothing Then
            'oParticipant = New Cdm.DataCore.Entities.Participant
            'Else

            Me.CasePersonalInfo.PrimaryObject = oParticipant
            Me.CaseProgramInfo.PrimaryObject = oParticipant
            Me.CaseEmployee.ParticipantObject = oParticipant
            Me.CaseMedicalProvider.ParticipantObject = oParticipant
            Me.CaseFMSA.PrimaryObject = oParticipant
            Me.CaseSupportBroker.PrimaryObject = oParticipant
            Me.CaseLegalGuardian.PrimaryObject = oParticipant.Guardian
            Me.CaseParticipantRepInfo.PrimaryObject = oParticipant.Representative
            Me.CaseUserInfo.PrimaryObject = oParticipant
            SetSubNavTabs()
            BindDropDowns()
            ' End If

        End If

        SetSaveVisible()
        SetPageControlProperties()
        Me.SuccessLabel.Visible = False

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Load

        Me.SuccessLabel.Visible = False
        EntityController.JavaScriptAddChildDiv(Me.FileDiv.ClientID, 80)
        EntityController.JavaScriptSetFixedHeight(30)

    End Sub

    Private Sub BindDropDowns()

        Me.caseStatus.DataSource = Cdm.DataCore.LookupTables.LuCaseStatus.ListAll(0, "Select Status")
        Me.caseStatus.DataBind()

    End Sub

    Private Sub SetSaveVisible()

        If UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CasePersonal) Then

            Me.SaveVisible = True

        ElseIf UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseEmployee) Or _
           UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseFinancial) Or _
           UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseFMSA) Or _
           UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseGuardianPermissions) Then

            Me.SaveVisible = True

        ElseIf UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseLegalGuardian) Or _
        UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseMedicalProvider) Or _
        UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseParticipantRep) Or _
        UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseProgramInfo) Or _
        UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseSupportBroker) Or _
        UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseUserInfo) Or _
        UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseRepPermissions) Then

            Me.SaveVisible = True

        Else

            Me.SaveVisible = False

        End If

        If Me.CaseMultiView.GetActiveView().Equals(Me.CaseNotesView) Then
            Me.SaveVisible = False
        ElseIf Me.CaseMultiView.GetActiveView().Equals(Me.DuplicateView) Then
            Me.SaveVisible = False
        ElseIf Me.CaseMultiView.GetActiveView().Equals(Me.DocumentsView) Then
            Me.SaveVisible = False
        End If

    End Sub

    ''' <summary>
    ''' Set the Visibility of the SubNav Tabs according to User Permissions
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetSubNavTabs()

        EditCaseSubNav1.DisplayNameList = System.Web.HttpContext.Current.Application("displayNames")
        EditCaseSubNav1.IsSmallToolbar = Not (UserAuthorization.CurrentUser.IsSingleParticipantUser())
        EditCaseSubNav1.ShowAffirmations = False
        EditCaseSubNav1.ShowCaseNotes = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseNotes)
        EditCaseSubNav1.ShowEmployeeInfo = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseEmployee)

        If IsSingleParticipantUser() Then
            EditCaseSubNav1.ShowFinancial = False
        Else
            EditCaseSubNav1.ShowFinancial = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseFinancial)
        End If

        EditCaseSubNav1.ShowFMSA = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseFMSA)
        EditCaseSubNav1.ShowLegalGuardianInfo = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseLegalGuardian)
        EditCaseSubNav1.ShowMedicalCareProvider = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseMedicalProvider)
        EditCaseSubNav1.ShowParticipantRepInfo = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseParticipantRep)
        EditCaseSubNav1.ShowPersonalInfo = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CasePersonal)
        EditCaseSubNav1.ShowProgram = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseProgramInfo)
        EditCaseSubNav1.ShowSupportBroker = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseSupportBroker)
        'NPO has requested that user info tab be removed for EVERYONE.
        EditCaseSubNav1.ShowUserInfo = False
        'EditCaseSubNav1.ShowUserInfo = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseUserInfo)
        EditCaseSubNav1.ShowAssessments = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.Assessments)
        EditCaseSubNav1.ShowDocuments = UserAuthorization.HasViewPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseDocuments)

        If oParticipant.ParticipantId = 0 Then
            EditCaseSubNav1.ShowCaseNotes = False
            EditCaseSubNav1.ShowFinancial = False
            'EditCaseSubNav1.ShowUserInfo = UserAuthorization.HasInsertPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseUserInfo)
        End If

    End Sub

    Private Function IsSingleParticipantUser() As Boolean

        Select Case UserAuthorization.CurrentUser.RoleId

            Case Convert.ToInt32(Cdm.DataCore.UserSecurity.Role.RoleType.LegalGuardian), _
                 Convert.ToInt32(Cdm.DataCore.UserSecurity.Role.RoleType.Representative), _
                 Convert.ToInt32(Cdm.DataCore.UserSecurity.Role.RoleType.Participant)
                Return True

            Case Else
                Return False

        End Select

    End Function

    Private Sub SetPageControlProperties()

        Dim setValues As Boolean = Not (Me.IsPostBack)
        Me.DisplayNameLabel.Text = oParticipant.FullName
        Me.caseStatus.cssClassLabel = "partHeader"
        Me.caseStatus.Editable = False
        Me.caseStatus.Value = oParticipant.CaseStatusId.ToString()

        If Not Me.caseStatus.Editable Then
            Me.caseStatus.cssClassControl = "partHeaderResult"
        Else
            Me.caseStatus.cssClassControl = "formSelect"
        End If

        Me.caseStatus.Visible = True
        
    End Sub

    Protected Sub saveButton_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles saveButton.Click

        Dim isNew As Boolean = False
        If oParticipant.ParticipantId = 0 Then isNew = True
        Dim transaction As New Gentle.Framework.Transaction
        oParticipant.Reset()
        If Not oParticipant.Representative Is Nothing Then
            oParticipant.Representative.Reset()
        End If
        If Not oParticipant.Guardian Is Nothing Then
            oParticipant.Guardian.Reset()
        End If
        oParticipant.LastModified = UserAuthorization.CurrentUser.LogonId
        oParticipant.HasRepresentative = Me.CaseParticipantRepInfo.IsParticipantRepChecked
        oParticipant.HasLegalGuardian = Me.CaseLegalGuardian.IsLegalGuardianChecked

        Dim previousStatusId As Integer = oParticipant.CaseStatusId
        Dim newStatusId As Integer = CInt(Me.CasePersonalInfo.CaseStatusSelection)

        Me.CasePersonalInfo.SaveData()
        Me.CaseProgramInfo.SaveData()
        Me.CaseLegalGuardian.SaveData()
        Me.CaseParticipantRepInfo.SaveData()

        EntityController.SetObjectPropertiesFromPage(Me.CaseUserInfo)
        If Not (Application("State") Is Nothing) Then
            oParticipant.StreetAddressState = Application("State").ToString()
        End If
        oParticipant.FMSAId = Me.CaseFMSA.FMSAId
        oParticipant.SupportBrokerId = Me.CaseSupportBroker.SupportBrokerId
        Dim duplicateParticipant As Cdm.DataCore.Entities.Participant = oParticipant.DuplicateSSNParticipant
        Dim duplicateMedicaidNumberParticipant As Cdm.DataCore.Entities.Participant = oParticipant.DuplicateMedicaidNumberParticipant
        If Not duplicateParticipant Is Nothing Then

            ShowDuplicateSSN(duplicateParticipant)

        ElseIf Not duplicateMedicaidNumberParticipant Is Nothing Then
            ShowDuplicateMedicaidNumber(duplicateMedicaidNumberParticipant)

        Else



            Dim errorlist As ArrayList = oParticipant.Validate()
            If errorlist.Count = 0 Then

                Try

                    SetEmailValues()
                    oParticipant.LastModified = UserAuthorization.CurrentUser.LogonId
                    oParticipant.DateModified = Now

                    If Application("AutoUpdateStatusOnEnrollmentDateChange") = "true" Then
                        If oParticipant.EnrollmentDateChanged And _
                            Not Year(oParticipant.DisenrollmentDate) > 1950 And _
                            Year(oParticipant.EnrollmentDate) > 1950 Then
                            oParticipant.CaseStatusId = 17002
                        End If
                    End If

                    oParticipant.Persist(transaction)

                    If previousStatusId <> newStatusId Then
                        RecordStatusHistory(isNew)
                    End If

                    ShowSuccess()
                    RefreshValues(isNew)

                Catch ex As Exception

                    Dim alError As ArrayList = New ArrayList
                    alError.Add(ex.Message)
                    ShowError(alError)

                End Try

            Else

                ShowError(errorlist)

            End If

        End If

    End Sub

    ''' <summary>
    ''' When a participant's status has changed, create a status history object;
    ''' If status is a non-active one, 
    ''' redirect to a page where user can add status changes and commnets
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub RecordStatusHistory(ByVal isNewParticipantValue As Boolean)

        Dim statusHistory As New Cdm.DataCore.Entities.ParticipantStatusHistory()
        Dim currentDate As DateTime = DateTime.Now
        statusHistory.DateCreated = currentDate
        statusHistory.DateModified = currentDate
        statusHistory.EffectiveDate = currentDate
        statusHistory.ParticipantID = oParticipant.ParticipantId
        statusHistory.CaseStatusId = oParticipant.CaseStatusId
        statusHistory.LastModified = UserAuthorization.CurrentUser.LogonId
        statusHistory.Persist()

        If (Not oParticipant.IsActiveFile) And (Not isNewParticipantValue) Then
            Response.Redirect("ChangeStatus.aspx?id=" & statusHistory.ParticipantStatusHistoryId.ToString())
        End If

    End Sub

    ''' <summary>
    ''' Place the updated values in the 
    ''' </summary>
    ''' <param name="isNew"></param>
    ''' <remarks></remarks>
    Private Sub RefreshValues(ByVal isNew As Boolean)

        If isNew Then
            oParticipant.User.Refresh()
            Me.CaseUserInfo.SetUserNameAndPassword(oParticipant.LogonId, oParticipant.Password)
            Me.CasePersonalInfo.SetParticipantId(oParticipant.ParticipantId)
        End If

        Me.caseStatus.Value = oParticipant.CaseStatusId.ToString()
        Me.CasePersonalInfo.SetStatusId(oParticipant.CaseStatusId)
        Me.DisplayNameLabel.Text = oParticipant.FullName
        'If this is a new file, the notes and financial tabs may now be visible.
        SetSubNavTabs()
        Me.CaseProgramInfo.ShowDates()

    End Sub

    Private Sub ShowDuplicateSSN(ByVal duplicateParticipant As Cdm.DataCore.Entities.Participant)

        Dim errorMessage As String
        errorMessage = String.Format("The Social Security Number you entered is already in the system for another participant: {0}.  What would you like to do?", duplicateParticipant.FullName)
        Me.CaseMultiView.SetActiveView(Me.DuplicateView)
        Me.ValidationErrorDuplicate.SetSingleError(errorMessage)
        Me.GoToDuplicateButton.PostBackUrl = "~/case/casepersonal.aspx?participantid=" & duplicateParticipant.Id.ToString()
        If Me.oParticipant.Id > 0 Then
            Me.GoToDuplicateButton.Text = "View above file (cancels update)"
        Else
            Me.GoToDuplicateButton.Text = "View above file (cancels new File)"
        End If
        Me.GoToDuplicateButton.CommandArgument = "SSN"

    End Sub

    Private Sub ShowDuplicateMedicaidNumber(ByVal duplicateParticipant As Cdm.DataCore.Entities.Participant)
        Dim errorMessage As String
        errorMessage = String.Format("The Medicaid Number you entered is already in the system for another participant: {0}.  What would you like to do?", duplicateParticipant.FullName)
        Me.CaseMultiView.SetActiveView(Me.DuplicateView)
        Me.ValidationErrorDuplicate.SetSingleError(errorMessage)
        Me.GoToDuplicateButton.PostBackUrl = "~/case/casepersonal.aspx?participantid=" & duplicateParticipant.Id.ToString()
        If Me.oParticipant.Id > 0 Then
            Me.GoToDuplicateButton.Text = "View above file (cancels update)"
        Else
            Me.GoToDuplicateButton.Text = "View above file (cancels new File)"
        End If
        Me.GoToDuplicateButton.CommandArgument = "Medicaid"
    End Sub



    Private Sub SetEmailValues()

        Dim fromEmail As String = Application("EmailFromAddress")
        Dim emailServer As String = Application("EmailServer")
        Dim emailFromDisplayName As String = Application("EmailFromDisplayName")
        If String.IsNullOrEmpty(emailServer) Then
            emailServer = "localhost"
        End If
        Dim appHomePage As String = EntityController.ApplicationHomePage
        oParticipant.SetNotificationEmail(fromEmail, emailServer, emailFromDisplayName, appHomePage)

    End Sub

    Private Sub ShowSuccess()

        Me.SuccessLabel.Visible = True

    End Sub

    Private Sub ShowError(ByVal errorlist As ArrayList)

        Me.CaseMultiView.SetActiveView(Me.ResultsView)
        Me.ValidationErrorSummary1.Message = "Error Saving File"
        Me.ValidationErrorSummary1.SetErrors(errorlist)

    End Sub

    Protected Sub EditCaseSubNav1_ChangeMenu(ByVal sender As Object, _
                                             ByVal e As System.EventArgs) _
                                             Handles EditCaseSubNav1.ChangeMenu

        SetActiveView()

    End Sub

    Private Sub SetActiveView()

        Select Case EditCaseSubNav1.SelectedButton

            Case InputControls.EditCaseSubNav.BUTTON_AFFIRMATIONS
                Me.CaseMultiView.SetActiveView(Me.AffirmationsView)
            Case InputControls.EditCaseSubNav.BUTTON_CASENOTES
                Me.CaseMultiView.SetActiveView(Me.CaseNotesView)
            Case InputControls.EditCaseSubNav.BUTTON_EMPLOYEE
                Me.CaseMultiView.SetActiveView(Me.EmployeeView)
            Case InputControls.EditCaseSubNav.BUTTON_FINANCIAL
                Response.Redirect("~/Budget/SpendingPlanView.aspx")
            Case InputControls.EditCaseSubNav.BUTTON_FMSA
                Me.CaseMultiView.SetActiveView(Me.FMSAView)
            Case InputControls.EditCaseSubNav.BUTTON_LEGALGUARDIAN
                Me.CaseMultiView.SetActiveView(Me.GuardianView)
            Case InputControls.EditCaseSubNav.BUTTON_MEDICAL
                Me.CaseMultiView.SetActiveView(Me.MedicalView)
            Case InputControls.EditCaseSubNav.BUTTON_PARTICIPANTREP
                Me.CaseMultiView.SetActiveView(Me.RepView)
            Case InputControls.EditCaseSubNav.BUTTON_PERSONAL
                Me.CaseMultiView.SetActiveView(Me.PersonalInfoView)
            Case InputControls.EditCaseSubNav.BUTTON_PROGRAM
                Me.CaseMultiView.SetActiveView(Me.ProgramInfoView)
            Case InputControls.EditCaseSubNav.BUTTON_SUPPORTBROKER
                Me.CaseMultiView.SetActiveView(Me.SupportBrokerInfoView)
            Case InputControls.EditCaseSubNav.BUTTON_USERINFO
                Me.CaseMultiView.SetActiveView(Me.UserInfoView)
            Case InputControls.EditCaseSubNav.BUTTON_DOCUMENTS
                Me.CaseMultiView.SetActiveView(Me.DocumentsView)
            Case InputControls.EditCaseSubNav.BUTTON_ASSESSMENTS
                Response.Redirect(ConfigurationManager.AppSettings("AssessmentsUrl"))

        End Select

        Me.Title = "File - " & EntityController.GetSingleDisplayName(Me.EditCaseSubNav1.SelectedButton)
        SetSaveVisible()

    End Sub

    Public Sub ResetControls() Implements IPermission.ResetControls

    End Sub

    Protected Sub returnToView_Click(ByVal sender As Object, _
                                     ByVal e As System.EventArgs) _
                                     Handles returnToView.Click

        SetActiveView()

    End Sub

    Protected Sub GoToDuplicateButton_Click(ByVal sender As Object, _
                                            ByVal e As System.EventArgs) _
                                            Handles GoToDuplicateButton.Click

        If Me.GoToDuplicateButton.CommandArgument.Equals("SSN") Then
            Server.Transfer("editFile.aspx?participantid=" & oParticipant.DuplicateSSNParticipant.ParticipantId.ToString())
        Else
            Server.Transfer("editFile.aspx?participantid=" & oParticipant.DuplicateMedicaidNumberParticipant.ParticipantId.ToString())
        End If

    End Sub

    Protected Sub ReturnToFileButton_Click(ByVal sender As Object, _
                                           ByVal e As System.EventArgs) _
                                           Handles ReturnToFileButton.Click

        Me.CaseMultiView.SetActiveView(Me.PersonalInfoView)

    End Sub

End Class
